package api

import (
	"crypto/sha256"
	"encoding/json"
	"fmt"
	"goProject/db"
	"goProject/public"
	"io"
	"net/http"
	"time"
)

type pUpload struct {
	Lang          string `json:"lang"`
	TimeoutSecond int64  `json:"timeout_second"`
	Content       string `json:"content"`
}

func Upload(w http.ResponseWriter, r *http.Request) {
	if r.ContentLength > 1024*1024*10 {
		w.Write(public.NewResp(http.StatusBadRequest, "参数错误：Content Length 不能超过 1024*1024*10", nil, nil).Bytes())
		return
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	body, err := io.ReadAll(r.Body)
	if err != nil {
		w.Write(public.NewResp(http.StatusBadRequest, "参数错误：无法读取请求体", nil, nil).Bytes())
		return
	}
	var p pUpload
	err = json.Unmarshal(body, &p)
	if err != nil {
		w.Write(public.NewResp(http.StatusBadRequest, "参数错误：json解码请求体失败", nil, nil).Bytes())
		return
	}
	if p.TimeoutSecond < 600 {
		p.TimeoutSecond = 600
	}
	if p.TimeoutSecond > 604800 {
		p.TimeoutSecond = 604800
	}
	sha := fmt.Sprintf("%x", sha256.Sum256([]byte(time.Now().String())))
	err = db.Redis.Set(fmt.Sprint("code_", sha), public.SaveRedisContent{
		Lang:    p.Lang,
		Exp:     time.Now().Unix() + p.TimeoutSecond,
		Content: p.Content,
	}.String(), time.Duration(p.TimeoutSecond)*time.Second).Err()
	if err != nil {
		w.Write(public.NewResp(http.StatusInternalServerError, "系统错误：保存内容到数据库失败", nil, nil).Bytes())
		return
	}
	w.Write(public.NewResp(http.StatusOK, "", sha, "").Bytes())
}
